package com.xy.Cache;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smsplatform.common.constants.CacheConstants;
import com.xy.Feign.CacheFeign.CacheService;
import com.xy.pojo.TPublicParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 存放的是我们公开参数的缓存
 * @Author: xiaoyang
 * @Date: 2022/11/20/20:31
 * @Description:
 */
@Component
public class PublicParamsCache {

    CacheService cacheService;

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    List<TPublicParams> publicParams=new ArrayList<>(); //保存所有公共参数的集合

    public List<TPublicParams> getPublicParams() {
        return publicParams;
    }

    /**
     * 初始化数据
     */
    @PostConstruct
    public void init() {

        //数据在缓存中保存,所以我们需要从缓存中获取数据
        List<LinkedHashMap> result = (List<LinkedHashMap>) cacheService.getObject(CacheConstants.CACHE_PUBLICPARAMS_KEY);
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, TPublicParams.class);//我们期望的返回结果是list
        try {
            Object value = objectMapper.readValue(objectMapper.writeValueAsString(result), javaType);//从map转回json再转回对象
            publicParams.clear();
            publicParams.addAll((Collection<? extends TPublicParams>) value);
            System.err.println("初始化公共参数的本地缓存:" + publicParams);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }

}
